﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using COFE.Core.Filter;
using System.Linq.Expressions;
using COFE.Core;
using COFE.Core.Lister;
using COFE.Data.Utils.ThirdParty;

namespace COFE.Data.Filter
{
    public class RootEntryFilterExpression : 
        EntryFilterExpression<COFE.Core.Filter.RootEntryFilter>
    {
        public RootEntryFilterExpression()
            :base()
        {

        }

        public override Expression<Func<Entry, bool>> getExpression(
            IEntryFilter f, IOptionFilter[] options)
        {
            System.Linq.Expressions.Expression<Func<Entry, bool>> exp = null;

            var filter = f as COFE.Core.Filter.RootEntryFilter;
            string fullPath = filter.Directory.ParseName;
            Guid id = filter.Directory.GetId();
            string key, parsePath;
            COFEPath.ParseFullParseName(fullPath, out key, out parsePath);
            bool isRootDirectory = fullPath == ProfileRootDirectoryLister.ProfileRootListerKey ||
                fullPath == ProfileRootDirectoryLister.ProfileRootParsablePath;

            switch (options.GetSearchOption())
            {
                case SearchOptionEx.TopDirectoryOnly:
                    exp = (e) => e.ParentId == id;
                    break;

                case SearchOptionEx.AllDirectories:
                    if (isRootDirectory)
                        exp = (e) => e.PrimaryVolumeId == e.SecondaryVolumeId;
                    else
                        if (parsePath == "")
                            exp = (e) => e.SecondaryVolumeId == key &&
                                e.ParsePath != parsePath;
                        else
                            exp = (e) => e.SecondaryVolumeId == key &&
                                e.ParsePath != parsePath &&
                                e.ParsePath.StartsWith(parsePath);

                    break;
                case SearchOptionEx.AllDirectoriesAndFileBasedFS:
                    if (isRootDirectory)
                        exp = (e) => true;
                    else
                        if (parsePath == "")
                            exp = (e) => e.PrimaryVolumeId == key &&
                                e.ParsePath != parsePath;
                        else
                            exp = (e) => e.PrimaryVolumeId == key &&
                                e.ParsePath != parsePath &&
                                e.ParsePath.StartsWith(parsePath);
                    break;

                default:
                    throw new NotSupportedException();
            }

            if (f.Negative)
                return exp.Not();
            return exp;
        }

        



    }


    //class RootEntryFilterExpression
    //{
    //    

    //}
}
